package com.lonwin.inspectionmanagement.mvp.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.geocoder.StreetNumber;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hss01248.dialog.StyledDialog;
import com.hss01248.dialog.interfaces.MyDialogListener;
import com.hss01248.dialog.interfaces.MyItemDialogListener;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.lh.LhEarthSurfaceView;
import com.lh.LhSmoothEarthSurfaceView;
import com.lh.features.LhCoordinate;
import com.liji.imagezoom.util.ImageZoom;
import com.lonwin.inspectionmanagement.R;
import com.lonwin.inspectionmanagement.R2;
import com.lonwin.inspectionmanagement.app.AppConstants;
import com.lonwin.inspectionmanagement.app.Glide4Engine;
import com.lonwin.inspectionmanagement.app.service.PlayService;
import com.lonwin.inspectionmanagement.app.utils.AppCache;
import com.lonwin.inspectionmanagement.app.utils.AppUtil;
import com.lonwin.inspectionmanagement.app.utils.DataUtil;
import com.lonwin.inspectionmanagement.app.utils.GPSUtil;
import com.lonwin.inspectionmanagement.app.utils.LhEarthUtils;
import com.lonwin.inspectionmanagement.app.utils.Listener.LhEarthListener;
import com.lonwin.inspectionmanagement.app.utils.SpaceItemDecoration;
import com.lonwin.inspectionmanagement.di.component.DaggerCreatPointRecordComponent;
import com.lonwin.inspectionmanagement.di.module.CreatPointRecordModule;
import com.lonwin.inspectionmanagement.mvp.contract.CreatPointRecordContract;
import com.lonwin.inspectionmanagement.mvp.model.api.AppConstant;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ConfigBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.CreaQuestResultBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ImageBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.PointHistoryBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ProblemBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ResQdetailBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.SaveResultBean;
import com.lonwin.inspectionmanagement.mvp.presenter.CreatPointRecordPresenter;
import com.lonwin.inspectionmanagement.mvp.ui.adapter.OnePicAdapter;
import com.lonwin.inspectionmanagement.widget.dialog.LoadingDailog;
import com.lonwin.inspectionmanagement.widget.voicerecorder.widget.VoiceRecorderView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class CreatPointRecordActivity extends BaseActivity<CreatPointRecordPresenter> implements CreatPointRecordContract.View, LhEarthListener.ScreenMoveListener, OnGeocodeSearchListener {
    private final int REQUEST_CODE_CHOOSE = 12034;
    private final int REQUEST_CODE_VIDEO = 11034;
    private boolean isNeedRefresh = true;
    List<Uri> mSelected;
    @BindView(R2.id.back_icon)
    ImageView backIcon;
    @BindView(R2.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R2.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R2.id.back_right_icon)
    TextView backRight;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;

    @BindView(R2.id.creaPointRecord_LhEarthSurfaceView)
    LhEarthSurfaceView creaPointRecordLhEarthSurfaceView;

    @BindView(R2.id.creaPointRecord_address)
    EditText creaPointRecordAddress;
    @BindView(R2.id.creaPointRecord_type)
    TextView creaPointRecordType;
    @BindView(R2.id.creaPointRecord_descript)
    EditText creaPointRecordDescript;
    @BindView(R2.id.creaPointRecord_RecyclerView)
    RecyclerView creaPointRecordRecyclerView;
    @BindView(R2.id.creaPointRecord_record_lay)
    LinearLayout creaPointRecordrecordlay;
    @BindView(R2.id.voice_recorder)
    VoiceRecorderView voiceRecorderView;

    @BindView(R2.id.creaPointRecord_record_save)
    TextView saveToUpload;
    @BindView(R2.id.creaPointRecord_record_design)
    TextView creaPointRecordrecorddesign;

    @BindView(R2.id.creaPointRecord_lay_hh)
    LinearLayout creaPointRecord_lay_hh;

    @BindView(R2.id.creaPointRecord_hh)
    TextView creaPointRecord_hh;

    @BindView(R2.id.creaPointRecord_latLont)
    TextView creaPointRecord_latLont;
    //删除视频
    @BindView(R2.id.iv_videoclose)
    ImageView iv_videoclose;
    //删除音频
    @BindView(R2.id.iv_audioclose)
    ImageView iv_audioclose;
    @BindView(R2.id.tv_autiotime)
    TextView tvautiotime;
    @BindView(R2.id.iv_play)
    ImageView ivplay;
    @BindView(R2.id.btn_startrecord)
    Button btnstartrecord;
    @BindView(R2.id.ll_voice)
    LinearLayout ll_voice;
    @BindView(R2.id.creaPointRecord_record_video_img)
    ImageView creaPointRecordrecordvideoimg;

    @BindView(R2.id.orderevaluate_charnum_txt)
    TextView orderevaluate_charnum_txt;

    OnePicAdapter picAdapter;
    private GeocodeSearch geocodeSearch;
    private ImageBean selectedImageBean;
    private String autioPath;
    private ResQdetailBean.DataBean dataBean;
    private LhCoordinate mlhCoordinate;
    private int voiceTime = 0;
    private LoadingDailog loadingDailog;
    PlayServiceConnection mPlayServiceConnection;
    private List<ResQdetailBean.DataBean.QusetTypeTempRelBean> mQusetTypeTempRelBeans = new ArrayList<>();
    private List<ResQdetailBean.DataBean.QusetAttrTempRelBean> mAttrTempRelBeans = new ArrayList<ResQdetailBean.DataBean.QusetAttrTempRelBean>();
    private String videoId;
    private String videoPicId;
    private int videoTime;

    public enum Type implements Serializable {
        ADD, EDIT, PUB, ONLYONE, LOOK,HANDOVER
    }

    /**
     * 问题id
     */
    private String qid;
    private Type mode;
    private  String videopath="";
    AnimationDrawable anim;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerCreatPointRecordComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .creatPointRecordModule(new CreatPointRecordModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_creat_point_record; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        if (!TextUtils.isEmpty(qid) && isNeedRefresh) {
            mPresenter.loadDetail(qid);
        }
        isNeedRefresh = true;
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    private void startPlayService() {
        Intent intent = new Intent();
        intent.setClass(CreatPointRecordActivity.this, PlayService.class);
        mPlayServiceConnection = new PlayServiceConnection();
        bindService(intent, mPlayServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private void unbindService() {
        unbindService(mPlayServiceConnection);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        loadingDailog = new LoadingDailog.Builder(this).setMessage("处理中...").create();
        mPresenter.initPhoto();
        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        startPlayService();
        creaPointRecordDescript.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 100) {
                    editable.delete(100, editable.length());
                }
                orderevaluate_charnum_txt.setText(editable.length() + "/100");

            }
        });
        ivplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppCache.getPlayService() != null) {
                    //  AppCache.getPlayService().play("http://img.layuva.com//b96c4bde124a328d9c6edb5b7d51afb2.amr");
//                    AppCache.getPlayService().play(AppUtil.prePicUrl() + autioPath);
                    AppCache.getPlayService().play(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+autioPath);
                }
            }
        });
        findViewById(R.id.creaPointRecord_record_video_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(videopath))
                {
                    VideoPlayer.play(CreatPointRecordActivity.this,videopath,"");

                    return;
                }
                if (dataBean!=null&&dataBean.getQusetAttrTempRel()!=null&&!dataBean.getQusetAttrTempRel().isEmpty()&&!TextUtils.isEmpty(dataBean.getQusetAttrTempRel().get(0).getCoverid())){
                     VideoPlayer.play(CreatPointRecordActivity.this,DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getQusetAttrTempRel().get(0).getAttrid(),"");
                    return;
                }
                if (mode==Type.PUB||mode==Type.LOOK||mode==Type.HANDOVER){
//                    showMessage("公开状态不能编辑视频");
                    return;
                }
                startVideo();
            }
        });
        LhEarthUtils.addLayers(creaPointRecordLhEarthSurfaceView,mPresenter.getConfigBean());
        creaPointRecordLhEarthSurfaceView.setInputHandler(new LhEarthListener(this, creaPointRecordLhEarthSurfaceView));
        if (getIntent() != null) {
            mode = (Type) getIntent().getSerializableExtra(AppConstants.EXTRA_INT);
            qid = getIntent().getStringExtra(AppConstants.EXTRA_STRING_ID);
            picAdapter.setType(mode);
            findViewById(R.id.cl_record_design).setVisibility(View.GONE);
            if (mode != null) {
                switch (mode) {
                    case ADD:
                        creaPointRecord_lay_hh.setVisibility(View.GONE);
                        backRight.setVisibility(View.GONE);
                        addModeInitView();
                        break;
                    case PUB:
                    case EDIT:
                    case HANDOVER:
                        creaPointRecord_lay_hh.setVisibility(View.VISIBLE);
                        if (!TextUtils.isEmpty(qid)) {
                            mPresenter.loadDetail(qid);
                        }
                        break;
                    case ONLYONE:
                        creaPointRecord_lay_hh.setVisibility(View.VISIBLE);
                        saveToUpload.setText("保存");
                        backRight.setText("删除");
                        if (!TextUtils.isEmpty(qid)) {
                            mPresenter.loadDetail(qid);
                        }
                    case LOOK:

                        if (!TextUtils.isEmpty(qid)) {
                            mPresenter.loadDetail(qid);
                        }
                        break;
                    default:
                        finish();

                }
            }
        }
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                creaPointRecordrecordlay.setEnabled(aBoolean);
                if (!aBoolean) {
                    showMessage("请先打开录音权限");
                }
            }
        });
        initAuto();
        saveToUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mode == Type.PUB) {
//                    showMessage("提交逻辑");
                    mPresenter.publishPoint(dataBean.getQuestid());
                } else if (mode == Type.ADD) {
                    creaQuestResult();
                } else if (mode == Type.ONLYONE) {
//                    startCreatPointActivity(CreatPointRecordActivity.this, dataBean.getQuestid(), Type.ONLYONE, "编辑问题记录");
                    //保存
                    updateInfo();
                } else {
                   updateInfo();
                }

            }
        });
        backRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mode == Type.EDIT) {
                    StyledDialog.buildIosAlert("提示", "你确定要删除该条记录吗？", new MyDialogListener() {
                        @Override
                        public void onFirst() {
                            mPresenter.deletePoint(dataBean.getQuestid());
                        }

                        @Override
                        public void onSecond() {
                            StyledDialog.dismiss();
                        }
                    }).show();

                } else if (mode == Type.ONLYONE) {
//                    mPresenter.publishPoint(dataBean.getQuestid());
                    StyledDialog.buildIosAlert("提示", "你确定要删除该条记录吗？", new MyDialogListener() {
                        @Override
                        public void onFirst() {
                            mPresenter.deletePoint(dataBean.getQuestid());
                        }

                        @Override
                        public void onSecond() {
                            StyledDialog.dismiss();
                        }
                    }).show();
                } else {
                    startCreatPointActivity(CreatPointRecordActivity.this, dataBean.getQuestid(), Type.EDIT, "编辑问题记录");
                }
            }
        });
        if (mode == Type.ADD || mode == Type.EDIT||mode==Type.ONLYONE) {
            creaPointRecordType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showTypeDialog();
                }
            });
            creaPointRecord_lay_hh.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(CreatPointRecordActivity.this, CruiseSearchActivity.class);
                    CreatPointRecordActivity.this.startActivityForResult(intent, 1001);
                }
            });
            iv_audioclose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    voiceTime = 0;
                    audioUpSuccess(null);
                }
            });
            iv_videoclose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    videoTime=0;
                    videopath="";
                    if (dataBean!=null)
                    {
                        dataBean.setQusetAttrTempRel(new ArrayList<>());
                    }
                    videoUpSuccess(null);
                }
            });
        }

    }

    private void initAuto() {
        if (mode == Type.PUB || mode == Type.LOOK) return;
//        voiceRecorderView.setCustomNamingFile(true,System.currentTimeMillis()+".mp3");
        btnstartrecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new VoiceRecorderView.EaseVoiceRecorderCallback() {

                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        voiceTime = voiceTimeLength;
                        Log.e("voiceFilePath=", voiceFilePath + "  time = " + voiceTimeLength);
                        /**
                         *voiceFilePath 为录音文件存放在sd的路径
                         * voiceTimeLength 录音文件的时长
                         */
                        File file = new File(voiceFilePath);
                        if (file.exists()) {
                            mPresenter.uploadFile(file, 2);
                        }
                    }
                });
            }
        });
    }

    /**
     * 只能查看
     */
    private void onlyLook() {
        saveToUpload.setVisibility(View.GONE);
        backRight.setVisibility(View.GONE);
        if (dataBean == null) return;
        creaPointRecordAddress.setText(dataBean.getAddr());
        creaPointRecordAddress.setEnabled(false);
        creaPointRecordAddress.setFocusable(false);
        creaPointRecordDescript.setText(dataBean.getContent());
        creaPointRecordDescript.setEnabled(false);
        creaPointRecordDescript.setFocusable(false);
        creaPointRecordDescript.setKeyListener(null);
        creaPointRecord_latLont.setText(String.format("%.7f", dataBean.getX()) + "," + String.format("%.7f", dataBean.getY()));
        if (!TextUtils.isEmpty(dataBean.getGroupnm())) {
            creaPointRecord_hh.setText(dataBean.getGroupnm());
        } else {
            creaPointRecord_hh.setText("请选择河湖");
        }
        creaPointRecord_hh.setEnabled(false);
        creaPointRecord_hh.setFocusable(false);
        if (dataBean != null && dataBean.getQusetTypeTempRel().size() > 0) {
            if (!TextUtils.isEmpty(dataBean.getQusetTypeTempRel().get(0).getQuestTypenm())) {
                creaPointRecordType.setText(dataBean.getQusetTypeTempRel().get(0).getQuestTypenm());
            }

        }

      LhEarthUtils.locatPosition(creaPointRecordLhEarthSurfaceView, LhCoordinate.fromDegrees(dataBean.getY(), dataBean.getX()));//25.07263654159436,102.66734565340529
      if (!TextUtils.isEmpty(dataBean.getImg1())) {
          picAdapter.getData().get(0).setId(dataBean.getImg1());
          picAdapter.getData().get(0).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg1());
      }
      if (!TextUtils.isEmpty(dataBean.getImg2())) {
          picAdapter.getData().get(1).setId(dataBean.getImg2());
          picAdapter.getData().get(1).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+ dataBean.getImg2());
      }
      if (!TextUtils.isEmpty(dataBean.getImg3())) {
          picAdapter.getData().get(2).setId(dataBean.getImg3());
          picAdapter.getData().get(2).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+ dataBean.getImg3());
      }
      if (!TextUtils.isEmpty(dataBean.getImg4())) {
          picAdapter.getData().get(3).setId(dataBean.getImg4());
          picAdapter.getData().get(3).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg4());
      }

        if (!TextUtils.isEmpty(dataBean.getAudio())) {
            voiceTime = Integer.parseInt(dataBean.getAudiotm());
            audioUpSuccess(dataBean.getAudio());
        }
        if (dataBean.getQusetAttrTempRel()!=null&&!dataBean.getQusetAttrTempRel().isEmpty()&&!TextUtils.isEmpty(dataBean.getQusetAttrTempRel().get(0).getCoverid())){
            Glide.with(this).load(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getQusetAttrTempRel().get(0).getCoverid()).into(creaPointRecordrecordvideoimg);
        }
        picAdapter.notifyDataSetChanged();
    }

    private void editModeInitView() {
        if (dataBean == null) return;
        backRight.setText("删除");
        creaPointRecordAddress.setText(dataBean.getAddr());
        creaPointRecordDescript.setText(dataBean.getContent());
        iv_videoclose.setVisibility(View.VISIBLE);
        creaPointRecord_latLont.setText(String.format("%.7f", dataBean.getX()) + "," + String.format("%.7f", dataBean.getY()));
        if (!TextUtils.isEmpty(dataBean.getGroupnm())) {
            creaPointRecord_hh.setText(dataBean.getGroupnm());
        } else {
            creaPointRecord_hh.setText("请选择河湖");
        }

        if (mPresenter.getConfigBean().getRiverDatas()!=null&&mPresenter.getConfigBean().getRiverDatas().size()==1&&mPresenter.getConfigBean().getRiverDatas().get(0).getChildren()!=null&&mPresenter.getConfigBean().getRiverDatas().get(0).getChildren().size()==1)
        {
            creaPointRecord_lay_hh.setVisibility(View.VISIBLE);
        }
        if (dataBean != null && dataBean.getQusetTypeTempRel().size() > 0) {
            if (!TextUtils.isEmpty(dataBean.getQusetTypeTempRel().get(0).getQuestTypenm())) {
                creaPointRecordType.setText(dataBean.getQusetTypeTempRel().get(0).getQuestTypenm());
            }

        }
        LhEarthUtils.locatPosition(creaPointRecordLhEarthSurfaceView, LhCoordinate.fromDegrees(dataBean.getY(), dataBean.getX()));//25.07263654159436,102.66734565340529
        if (!TextUtils.isEmpty(dataBean.getImg1())) {
            picAdapter.getData().get(0).setId(dataBean.getImg1());
            picAdapter.getData().get(0).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg1());
        }
        if (!TextUtils.isEmpty(dataBean.getImg2())) {
            picAdapter.getData().get(1).setId(dataBean.getImg2());
            picAdapter.getData().get(1).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg2());
        }
        if (!TextUtils.isEmpty(dataBean.getImg3())) {
            picAdapter.getData().get(2).setId(dataBean.getImg3());
            picAdapter.getData().get(2).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+ dataBean.getImg3());
        }
        if (!TextUtils.isEmpty(dataBean.getImg4())) {
            picAdapter.getData().get(3).setId(dataBean.getImg4());
            picAdapter.getData().get(3).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg4());
        }

        if (!TextUtils.isEmpty(dataBean.getAudio())) {
            voiceTime = Integer.parseInt(dataBean.getAudiotm());
            audioUpSuccess(dataBean.getAudio());
        }
        if (dataBean.getQusetAttrTempRel()!=null&&!dataBean.getQusetAttrTempRel().isEmpty()&&!TextUtils.isEmpty(dataBean.getQusetAttrTempRel().get(0).getCoverid())){
            Glide.with(this).load(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getQusetAttrTempRel().get(0).getCoverid()).into(creaPointRecordrecordvideoimg);
            videoTime=dataBean.getQusetAttrTempRel().get(0).getAttrsize();
            videoUpSuccess(dataBean.getQusetAttrTempRel().get(0).getAttrid());
        }else {
            iv_videoclose.setVisibility(View.GONE);
        }
        picAdapter.notifyDataSetChanged();
    }


    public void creaQuestResult() {
        ConfigBean configBean = DataHelper.getDeviceData(this, AppConstants.EXTRA_CONFIG_DATA);
        Map<String, Object> maps = new HashMap<>();
        maps.put("adcd", configBean.getAdcd());
        maps.put("adcdnm", configBean.getAdcdName());
        maps.put("addr", creaPointRecordAddress.getText().toString());
        if (!TextUtils.isEmpty(autioPath)) {
            maps.put("audio", autioPath);
        }
        maps.put("audiotm", voiceTime);

        maps.put("content", creaPointRecordDescript.getText().toString());
        maps.put("gpsid", configBean.getGpsId());
        maps.put("gpsnm", configBean.getGpsName());

        if (mlhCoordinate == null) {
            maps.put("x", getIntent().getDoubleExtra("lont", 0));
            maps.put("y", getIntent().getDoubleExtra("lat", 0));
        } else {
            maps.put("x", mlhCoordinate.getLongitude());
            maps.put("y", mlhCoordinate.getLatitude());
        }
        List<String> paths = getUpladUrl();
        if (!paths.isEmpty()) {
            for (int m = 0; m < paths.size(); m++) {
                switch (m) {
                    case 0:
                        maps.put("img1", paths.get(m));
                        break;
                    case 1:
                        maps.put("img2", paths.get(m));
                        break;
                    case 2:
                        maps.put("img3", paths.get(m));
                        break;
                    case 3:
                        maps.put("img4", paths.get(m));
                        break;
                }
            }
        }
        if (mQusetTypeTempRelBeans.size() == 0) {
            if (configBean != null) {
                List<ConfigBean.XcglMenuBean> datas = configBean.getXcglMenu();
                ResQdetailBean.DataBean.QusetTypeTempRelBean bean = new ResQdetailBean.DataBean.QusetTypeTempRelBean();
                bean.setId(datas.get(0).getModuleID() + "");
                bean.setQuestType(Integer.parseInt(datas.get(0).getClassName()));
                bean.setQuestTypenm(datas.get(0).getModuleName() + "");
                if (dataBean != null) {
                    bean.setQuestid(dataBean.getQuestid());
                }
                mQusetTypeTempRelBeans.add(bean);
            }

        }
        maps.put("qusetTypeTempRel", new Gson().toJson(mQusetTypeTempRelBeans));
        if (videoPicId!=null&&videoId!=null){
            mAttrTempRelBeans.clear();
            ResQdetailBean.DataBean.QusetAttrTempRelBean attrTempRelBean=new ResQdetailBean.DataBean.QusetAttrTempRelBean();
            attrTempRelBean.setAttrid(videoId);
            attrTempRelBean.setCoverid(videoPicId);
            attrTempRelBean.setAttrnm("视频上传");
            attrTempRelBean.setAttrpostfix("mp4");
            attrTempRelBean.setAttrsize(videoTime);
            attrTempRelBean.setAttrtype(0);
            mAttrTempRelBeans.add(attrTempRelBean);
            maps.put("qusetAttrTempRel", new Gson().toJson(mAttrTempRelBeans));
        }
        mPresenter.creaQuestResult(maps);
    }


    @Override
    public void showLoading() {
        loadingDailog.show();
    }

    @Override
    public void hideLoading() {
        loadingDailog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void initPicRecylerView(List<ImageBean> imageBeans) {
        picAdapter = new OnePicAdapter(imageBeans);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        creaPointRecordRecyclerView.setLayoutManager(linearLayoutManager);
        creaPointRecordRecyclerView.addItemDecoration(new SpaceItemDecoration(dp2px(10)));
        creaPointRecordRecyclerView.setAdapter(picAdapter);
        if (mode == Type.PUB) return;
        picAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<String> temPaths = new ArrayList<>();
                for (ImageBean imageBean : picAdapter.getData()) {
                    if (imageBean.getId() != null && !TextUtils.isEmpty(imageBean.getId())) {
                        temPaths.add(imageBean.getUrl());
                    }
                }
                if (picAdapter.getData().get(position).getId() != null && !TextUtils.isEmpty(picAdapter.getData().get(position).getId())) {
                    ImageZoom.show(CreatPointRecordActivity.this, picAdapter.getData().get(position).getUrl(), temPaths);
                   return;
                }
                if (mode == Type.PUB || mode == Type.LOOK) {
                    return;
                }

                selectedImageBean = picAdapter.getItem(position);
                Matisse.from(CreatPointRecordActivity.this)
                        .choose(MimeType.ofImage())
                        .countable(true)
                        .capture(true)
                        .captureStrategy(
//                new CaptureStrategy(true, "com.lxc.inspectionmanagement.fileprovider"))
                new CaptureStrategy(true, getPackageName() +".inspectionmanagement.fileprovider"))
                        .maxSelectable(1)
                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(new Glide4Engine())
                        .forResult(REQUEST_CODE_CHOOSE);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        isNeedRefresh = false;
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            if (mSelected!=null&&!mSelected.isEmpty())
            {
                AppUtil.getBitmapFromUri(this,mSelected.get(0));
            }
            Log.d("Matisse", "mSelected: " + mSelected);
            if (!mSelected.isEmpty()) {
                selectedImageBean.setUrl(mSelected.get(0).toString());
                picAdapter.notifyDataSetChanged();
                String path = AppUtil.getFromMediaUri(this, getContentResolver(), mSelected.get(0));
                if (!TextUtils.isEmpty(path)) {
                    File file = new File(path);
                    if (file != null && file.exists()) {
                        Luban.with(this)
                                .load(file)
                                .ignoreBy(100)
                                //                                .setTargetDir()
                                .filter(new CompressionPredicate() {
                                    @Override
                                    public boolean apply(String path) {
                                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                                    }
                                })
                                .setCompressListener(new OnCompressListener() {
                                    @Override
                                    public void onStart() {
                                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        // TODO 压缩成功后调用，返回压缩后的图片文件
                                        mPresenter.uploadFile(file, 1);
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        // TODO 当压缩过程出现问题时调用
                                    }
                                }).launch();

                    }
                }

            }
        } else if (requestCode == 1001 && data != null) {
            ConfigBean.RiverDatasBean.ChildrenBean childrenBean = (ConfigBean.RiverDatasBean.ChildrenBean) data.getSerializableExtra("ChildrenBean");
            if (childrenBean == null) {
                showMessage("选择河湖失败");
                return;
            }
            dataBean.setGroupnm(childrenBean.getName());
            dataBean.setGroupid(childrenBean.getId());
            creaPointRecord_hh.setText(childrenBean.getName());
        } else if (requestCode == REQUEST_CODE_VIDEO && data != null) {
            videopath = data.getStringExtra("videopath");
            String picpath = data.getStringExtra("picpath");
            videoTime = data.getIntExtra("videotime", 0);
            mPresenter.uploadFile(new File(videopath), 3);
            if (!TextUtils.isEmpty(picpath)) {
                mPresenter.uploadFile(new File(picpath), 4);
            }
//            showMessage("视频地址："+videopath+"图片地址："+picpath);
        } else if (requestCode == 2001 && resultCode == RESULT_OK)
        {
            //从选择联系人返回
            killMyself();
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
        StringBuilder temAdderss = new StringBuilder();
        String province = regeocodeAddress.getProvince();//省
        String city = regeocodeAddress.getCity();//州市
        String count = regeocodeAddress.getDistrict();//县区
        String shipaddress = regeocodeAddress.getTownship();//村、街道
        String formataddress = regeocodeAddress.getFormatAddress();//完整的地址
        StreetNumber streetNumber = regeocodeAddress.getStreetNumber();//具体哪条路和门牌号
        String streetNumberStr = streetNumber.getStreet() + streetNumber.getNumber();//具体哪条路和门牌号字符串
        int index = formataddress.indexOf(shipaddress);
        String mapaddress = formataddress.substring(index + shipaddress.length(), formataddress.length());

        String temHtml = "";
        String firstAddress = "";
        String subAddress = "";
        if (formataddress.length() > temAdderss.append(province).append(city).append(count).append(shipaddress).toString().length()) {
            temHtml = "<font color='#494949'size='14'>" + formataddress.substring(temAdderss.length(), formataddress.length()) + "</font><br> <font color='#888888'size='10'>" + count + shipaddress + "</font>";
            firstAddress = formataddress.substring(temAdderss.length(), formataddress.length());
            subAddress = count + shipaddress;
        } else {
            if (shipaddress != null && shipaddress.length() > 0) {
                temHtml = "<font color='#494949'size='14'>" + shipaddress + "</font><br> <font color='#888888'size='10'>" + city + count + "</font>";
                firstAddress = shipaddress;
                subAddress = city + count;
            } else {
                temHtml = "<font color='#494949'size='14'>" + city + count + "</font><br> <font color='#888888'size='10'>" + province + "</font>";
                firstAddress = city + count;
                subAddress = province;
            }
        }
        if (mode == Type.ADD || mode == Type.EDIT) {
//            creaPointRecordAddress.setText(mapaddress);
            creaPointRecordAddress.setText(firstAddress);
        }


    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Override
    public void onMoveListener(LhCoordinate lhCoordinate) {
        mlhCoordinate = lhCoordinate;
        //移动后获取导经纬度
//        LatLonPoint latLonPoint = new LatLonPoint(lhCoordinate.getLatitude(), lhCoordinate.getLongitude());
        //wgs84 转高德坐标系
        double[] latlont = GPSUtil.gps84_To_Gcj02(lhCoordinate.getLatitude(), lhCoordinate.getLongitude());
        LatLonPoint latLonPoint = new LatLonPoint(latlont[0], latlont[1]);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 100f, GeocodeSearch.AMAP);
        //异步查询
        geocodeSearch.getFromLocationAsyn(query);
        if (mode == Type.EDIT || mode == Type.ADD) {
            creaPointRecord_latLont.setText(String.format("%.7f", mlhCoordinate.getLongitude()) + "," + String.format("%.7f", mlhCoordinate.getLatitude()));
        }
    }


    @Override
    public void audioUpSuccess(String path) {
        autioPath = path;
        if (voiceTime > 0) {
            ll_voice.setVisibility(View.VISIBLE);
            btnstartrecord.setVisibility(View.GONE);
            tvautiotime.setText(voiceTime + "s");
            if (mode == Type.PUB||mode==Type.LOOK||mode==Type.HANDOVER) return;
            iv_audioclose.setVisibility(View.VISIBLE);
        } else {
            btnstartrecord.setVisibility(View.VISIBLE);
            ll_voice.setVisibility(View.GONE);
            iv_audioclose.setVisibility(View.GONE);
        }
    }

    @Override
    public void imgUpSuccess(String path) {
        selectedImageBean.setId(path);
        for (int i = 0; i < picAdapter.getData().size(); i++) {
            if (dataBean != null) {
                if (i == 0) {
                    dataBean.setImg1(picAdapter.getData().get(0).getId());
                } else if (i == 1) {
                    dataBean.setImg2(picAdapter.getData().get(1).getId());
                } else if (i == 2) {
                    dataBean.setImg3(picAdapter.getData().get(2).getId());
                } else if (i == 3) {
                    dataBean.setImg4(picAdapter.getData().get(3).getId());
                }

            }
        }

    }


    /**
     * 获取所有上传相片的path
     */
    private List<String> getUpladUrl() {
        List<String> pathlist = new ArrayList<>();
        List<ImageBean> imageBeans = picAdapter.getData();
        for (ImageBean item : imageBeans) {
            if (!TextUtils.isEmpty(item.getId())) {
                pathlist.add(item.getId());
            }
        }
        return pathlist;
    }

    @Override
    public void showMultilChoice(List<ProblemBean> problemBeans) {
        //        MaterialDialog materialDialog=new MaterialDialog(this);

    }

    @Override
    public void savePointDataSuccess(SaveResultBean saveResultBean) {
        if (saveResultBean == null) {
            showMessage("提交失败");
            dataBean = null;
            return;
        }
        if (!saveResultBean.getCode().equals("0")) {
            showMessage(saveResultBean.getInfo());
            dataBean = null;
            return;
        }
        DataHelper.setIntergerSF(this, AppConstant.SHOW_POINT_TS_KEY, 1);
        showMessage("提交成功");
        killMyself();
    }

    @Override
    public void editPointSuccess(PointHistoryBean.DataBean dataBean) {
        if (dataBean == null) {
            showMessage("编辑失败");
            return;
        }
        showMessage("编辑成功");
        killMyself();
    }

    @Override
    public void addQuestTempSuccess(CreaQuestResultBean.DataBean dataBean) {
        showMessage("创建成功");
        Intent intent = new Intent();
        intent.putExtra(AppConstant.CREATPOINT, dataBean);
        setResult(RESULT_OK, intent);
        killMyself();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     *
     * @param dpValue 虚拟像素
     * @return 像素
     */
    public static int dp2px(float dpValue) {
        return (int) (0.5f + dpValue * Resources.getSystem().getDisplayMetrics().density);
    }

    private void setTitle() {
        String title = getIntent().getStringExtra(AppConstants.EXTRA_STRING);
        if (!TextUtils.isEmpty(title)) {
            toolbarTitle.setText(title);
        }
    }

    private void pubModeInitView() {
//        findViewById(R.id.ll_save).setVisibility(View.GONE);
//        creaPointRecordrecorddesign.setVisibility(View.VISIBLE);
//        creaPointRecordrecorddesign.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showMessage("选择交办对象");
//            }
//        });
        if (dataBean == null) return;
        backRight.setText("编辑");
        backRight.setVisibility(View.GONE);
        creaPointRecordAddress.setEnabled(false);
        creaPointRecordDescript.setEnabled(false);
        if (!TextUtils.isEmpty(dataBean.getGpsnm())) {
            creaPointRecord_hh.setText(dataBean.getGroupnm());
        }
        creaPointRecordAddress.setText(dataBean.getAddr());
        creaPointRecordDescript.setText(dataBean.getContent());
        creaPointRecord_latLont.setText(String.format("%.7f", dataBean.getX()) + "," + String.format("%.7f", dataBean.getY()));
        LhEarthUtils.locatPosition(creaPointRecordLhEarthSurfaceView, LhCoordinate.fromDegrees(dataBean.getY(), dataBean.getX()));//25.07263654159436,102.66734565340529
        if (!TextUtils.isEmpty(dataBean.getImg1())) {
            picAdapter.getData().get(0).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg1());
            picAdapter.getData().get(0).setId(dataBean.getImg1());
        }
        if (!TextUtils.isEmpty(dataBean.getImg1())) {
            picAdapter.getData().get(1).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg2());
            picAdapter.getData().get(1).setId(dataBean.getImg2());
        }
        if (!TextUtils.isEmpty(dataBean.getImg1())) {
            picAdapter.getData().get(2).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg3());
            picAdapter.getData().get(2).setId(dataBean.getImg3());
        }
        if (!TextUtils.isEmpty(dataBean.getImg1())) {
            picAdapter.getData().get(3).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg4());
            picAdapter.getData().get(3).setId(dataBean.getImg4());
        }

        if (!TextUtils.isEmpty(dataBean.getAudio())) {
            voiceTime = Integer.parseInt(dataBean.getAudiotm());
            audioUpSuccess(dataBean.getAudio());
        }
        if (dataBean.getQusetAttrTempRel()!=null&&!dataBean.getQusetAttrTempRel().isEmpty()&&!TextUtils.isEmpty(dataBean.getQusetAttrTempRel().get(0).getCoverid())){
            Glide.with(this).load(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getQusetAttrTempRel().get(0).getCoverid()).into(creaPointRecordrecordvideoimg);
        }
        if (dataBean != null && dataBean.getQusetTypeTempRel().size() > 0) {
            if (!TextUtils.isEmpty(dataBean.getQusetTypeTempRel().get(0).getQuestTypenm())) {
                creaPointRecordType.setText(dataBean.getQusetTypeTempRel().get(0).getQuestTypenm());
            }

        }
        picAdapter.notifyDataSetChanged();
    }

    private void addModeInitView() {
        ConfigBean configBean = DataHelper.getDeviceData(this, AppConstants.EXTRA_CONFIG_DATA);
        List<ConfigBean.XcglMenuBean> datas = configBean.getXcglMenu();
        for (ConfigBean.XcglMenuBean data : datas) {
            data.text = data.getModuleName();
        }
        ResQdetailBean.DataBean.QusetTypeTempRelBean bean = new ResQdetailBean.DataBean.QusetTypeTempRelBean();
        bean.setId(datas.get(0).getModuleID() + "");
        bean.setQuestTypenm(datas.get(0).getModuleName() + "");
        bean.setQuestType(Integer.parseInt(datas.get(0).getClassName()));
        if (dataBean != null) {
            bean.setQuestid(dataBean.getQuestid());
        }
        mQusetTypeTempRelBeans.add(bean);

        creaPointRecordType.setText(datas.get(0).text);
        StyledDialog.dismiss();

        double[] latlont = GPSUtil.gps84_To_Gcj02(getIntent().getDoubleExtra("lat", 0), getIntent().getDoubleExtra("lont", 0));
        LatLonPoint latLonPoint = new LatLonPoint(latlont[0], latlont[1]);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 100f, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
        LhEarthUtils.locatPosition(creaPointRecordLhEarthSurfaceView, LhCoordinate.fromDegrees(getIntent().getDoubleExtra("lat", 0), getIntent().getDoubleExtra("lont", 0)));//25.07263654159436,102.66734565340529
        creaPointRecord_latLont.setText(String.format("%.7f", latLonPoint.getLongitude()) + "，" + String.format("%.7f", latLonPoint.getLatitude()));
    }

    /**
     * 请求问题详情 根据mode加载不同的显示
     *
     * @param newdataBean
     */
    @Override
    public void setDetailBean(ResQdetailBean.DataBean newdataBean) {
        this.dataBean = newdataBean;
        mQusetTypeTempRelBeans.clear();
        mQusetTypeTempRelBeans.addAll(dataBean.getQusetTypeTempRel());
        backRight.setVisibility(View.VISIBLE);
        if (mode == Type.PUB) {
            saveToUpload.setText("提交");
            pubModeInitView();
        } else if (mode == Type.EDIT || mode == Type.ONLYONE) {
            editModeInitView();
        } else if (mode == Type.LOOK) {
            onlyLook();
        } else if (mode==Type.HANDOVER){
            handoverInitView();
        }
    }

    private void handoverInitView() {
        findViewById(R.id.ll_save).setVisibility(View.GONE);
        findViewById(R.id.cl_record_design).setVisibility(View.VISIBLE);
        findViewById(R.id.cl_record_design).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(CreatPointRecordActivity.this,HandOverActivity.class);
                intent.putExtra(AppConstants.EXTRA_DATA,dataBean);
                startActivityForResult(intent,2001);
            }
        });
        if (dataBean == null) return;
        backRight.setText("编辑");
        backRight.setVisibility(View.GONE);
        creaPointRecordAddress.setEnabled(false);
        creaPointRecordDescript.setEnabled(false);
        if (!TextUtils.isEmpty(dataBean.getGpsnm())) {
            creaPointRecord_hh.setText(dataBean.getGroupnm());
        }
        creaPointRecordAddress.setText(dataBean.getAddr());
        creaPointRecordDescript.setText(dataBean.getContent());
        creaPointRecord_latLont.setText(String.format("%.7f", dataBean.getX()) + "," + String.format("%.7f", dataBean.getY()));
        LhEarthUtils.locatPosition(creaPointRecordLhEarthSurfaceView, LhCoordinate.fromDegrees(dataBean.getY(), dataBean.getX()));//25.07263654159436,102.66734565340529
        if (!TextUtils.isEmpty(dataBean.getImg1())) {
            picAdapter.getData().get(0).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg1());
            picAdapter.getData().get(0).setId(dataBean.getImg1());
        }
        if (!TextUtils.isEmpty(dataBean.getImg1())) {
            picAdapter.getData().get(1).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg2());
            picAdapter.getData().get(1).setId(dataBean.getImg2());
        }
        if (!TextUtils.isEmpty(dataBean.getImg1())) {
            picAdapter.getData().get(2).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg3());
            picAdapter.getData().get(2).setId(dataBean.getImg3());
        }
        if (!TextUtils.isEmpty(dataBean.getImg1())) {
            picAdapter.getData().get(3).setUrl(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getImg4());
            picAdapter.getData().get(3).setId(dataBean.getImg4());
        }

        if (!TextUtils.isEmpty(dataBean.getAudio())) {
            voiceTime = Integer.parseInt(dataBean.getAudiotm());
            audioUpSuccess(dataBean.getAudio());
        }
        if (dataBean != null && dataBean.getQusetTypeTempRel().size() > 0) {
            if (!TextUtils.isEmpty(dataBean.getQusetTypeTempRel().get(0).getQuestTypenm())) {
                creaPointRecordType.setText(dataBean.getQusetTypeTempRel().get(0).getQuestTypenm());
            }

        }
        if (dataBean.getQusetAttrTempRel()!=null&&!dataBean.getQusetAttrTempRel().isEmpty()&&!TextUtils.isEmpty(dataBean.getQusetAttrTempRel().get(0).getCoverid())){
            Glide.with(this).load(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+dataBean.getQusetAttrTempRel().get(0).getCoverid()).into(creaPointRecordrecordvideoimg);
        }
        picAdapter.notifyDataSetChanged();
    }

    /**
     * startActivityForResult 方式启动的时候
     *
     * @param context
     * @param id
     * @param mode
     * @param title
     * @param requestCode
     * @param lat
     * @param lont
     */
    public static void startCreatPointActivity(Activity context, String id, Type mode, String title, int requestCode, double lat, double lont) {
        Intent intent = new Intent(context, CreatPointRecordActivity.class);
        intent.putExtra(AppConstants.EXTRA_STRING_ID, id);
        intent.putExtra(AppConstants.EXTRA_INT, mode);
        intent.putExtra(AppConstants.EXTRA_STRING, title);
        intent.putExtra("lat", lat);
        intent.putExtra("lont", lont);
        context.startActivityForResult(intent, requestCode);

    }

    /**
     * @param context
     * @param mode    必须
     * @param title
     */
    public static void startCreatPointActivity(Context context, String id, Type mode, String title) {
        Intent intent = new Intent(context, CreatPointRecordActivity.class);
        intent.putExtra(AppConstants.EXTRA_STRING_ID, id);
        intent.putExtra(AppConstants.EXTRA_INT, mode);
        intent.putExtra(AppConstants.EXTRA_STRING, title);
        context.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setTitle();
    }

    @Override
    public void deleteSuccess() {
        showMessage("删除成功");
        finish();

    }

    @Override
    public void publishSuccess(ResQdetailBean resQdetailBean) {
        showMessage("提交成功");
        finish();
    }

    @Override
    public void updateSuccess(ResQdetailBean resQdetailBean) {
        showMessage("修改成功");
        finish();
    }

    private void showTypeDialog() {
        ConfigBean configBean = DataHelper.getDeviceData(this, AppConstants.EXTRA_CONFIG_DATA);
        List<ConfigBean.XcglMenuBean> datas = configBean.getXcglMenu();
        for (ConfigBean.XcglMenuBean data : datas) {
            data.text = data.getModuleName();
        }
        StyledDialog.buildBottomSheetLv("请选择类型", datas, "取消", new MyItemDialogListener() {
            @Override
            public void onItemClick(CharSequence charSequence, int i) {
//                showMessage(datas.get(i).text);
                mQusetTypeTempRelBeans.clear();
                List<ResQdetailBean.DataBean.QusetTypeTempRelBean> questBeans = mQusetTypeTempRelBeans;
                ResQdetailBean.DataBean.QusetTypeTempRelBean bean = new ResQdetailBean.DataBean.QusetTypeTempRelBean();
                bean.setId(datas.get(i).getModuleID() + "");
                bean.setQuestType(Integer.parseInt(datas.get(i).getClassName()));
                bean.setQuestTypenm(datas.get(i).getModuleName() + "");
                if (dataBean != null) {
                    bean.setQuestid(dataBean.getQuestid());
                }
                questBeans.add(bean);

                creaPointRecordType.setText(datas.get(i).text);
                StyledDialog.dismiss();
            }
        }).show();
    }

    private class PlayServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            final PlayService playService = ((PlayService.PlayBinder) service).getService();
            Log.e("onServiceConnected----", "onServiceConnected");
            AppCache.setPlayService(playService);
            AppCache.getPlayService().setImageView(ivplay);
            AppCache.getPlayService().stopPlayVoiceAnimation();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService();
    }


    private void startVideo() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                               @Override
                               public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean){
                                        Intent intent = new Intent();
                                        intent.setClass(CreatPointRecordActivity.this, VideoRecorderActivity.class);
                                        startActivityForResult(intent,REQUEST_CODE_VIDEO);
                                    }else {
                                        showMessage("请打开摄像头权限");
                                    }
                               }
                           }
                );

    }

    @Override
    public void videoUpSuccess(String path) {
        videoId=path;
        if (videoTime > 0) {
            iv_videoclose.setVisibility(View.GONE);
            if (mode == Type.PUB||mode==Type.LOOK||mode==Type.HANDOVER)
            {
                return;
            }
            iv_videoclose.setVisibility(View.VISIBLE);
        } else {
            iv_videoclose.setVisibility(View.GONE);
            creaPointRecordrecordvideoimg.setImageResource(R.drawable.app_photo_icon);
        }
    }

    @Override
    public void videoPicUpSuccess(String path) {
        videoPicId=path;
        if (!TextUtils.isEmpty(path)){
            Glide.with(this).load(DataUtil.getFileUrl(mPresenter.getConfigBean())+"/"+path).into(creaPointRecordrecordvideoimg);
        }
    }

    /**
     * 修改编辑提交
     */
    public void updateInfo(){
        if (dataBean != null) {
            dataBean.setContent(creaPointRecordDescript.getText().toString());
            dataBean.setQusetTypeTempRel(mQusetTypeTempRelBeans);
            dataBean.setAudio(autioPath);
            dataBean.setAudiotm(voiceTime + "");
            if (videoPicId!=null&&videoId!=null){
                mAttrTempRelBeans.clear();
                ResQdetailBean.DataBean.QusetAttrTempRelBean attrTempRelBean=new ResQdetailBean.DataBean.QusetAttrTempRelBean();
                attrTempRelBean.setAttrid(videoId);
                attrTempRelBean.setCoverid(videoPicId);
                attrTempRelBean.setAttrnm("视频上传");
                attrTempRelBean.setAttrpostfix("mp4");
                attrTempRelBean.setAttrsize(videoTime);
                attrTempRelBean.setAttrtype(0);
                mAttrTempRelBeans.add(attrTempRelBean);
                dataBean.setQusetAttrTempRel(mAttrTempRelBeans);
            }
            List<ImageBean> paths = picAdapter.getData();
            if (!paths.isEmpty()) {
                for (int m = 0; m < paths.size(); m++) {
                    switch (m) {
                        case 0:
                            dataBean.setImg1(paths.get(m).getId());
                            break;
                        case 1:
                            dataBean.setImg2(paths.get(m).getId());
                            break;
                        case 2:
                            dataBean.setImg3(paths.get(m).getId());
                            break;
                        case 3:
                            dataBean.setImg4(paths.get(m).getId());
                            break;
                    }
                }
            }
        }
        mPresenter.updatePoint(dataBean);
    }
}
